package com.googlecode.h0v3rk4rt.util;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;


/**
 * A utility class for displaying errors a bit more
 * gracefully and user-friendly-ly.
 * @author Nilay Kumar
 *
 */
public class GameError {

	private static final String title = "Oh noes! Your h0v3rk4rt just crashed!";
	private static final String noMessage = "The l4zy c0d3r didn't expect this...";
	
	public static void showErrorDialog(final Throwable t, final String genText, Component parentComponent) {
		final String gT = ((genText == null) ? noMessage : genText);
		final JButton detailsButton = new JButton("Show Details");
		final JButton abortButton = new JButton("Abort");
		final JOptionPane pane = new JOptionPane(gT, JOptionPane.ERROR_MESSAGE, JOptionPane.YES_NO_OPTION, null, new Object[] {detailsButton, abortButton});
		final JDialog dialog = pane.createDialog(parentComponent, title);
		final Writer result = new StringWriter();
		final PrintWriter printWriter = new PrintWriter(result);
		t.printStackTrace(printWriter);
		final String stackTrace = result.toString();
		detailsButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				String label = detailsButton.getText();
				if(label.startsWith("Show")) {
					pane.setMessage(gT + "\n" + stackTrace);
					detailsButton.setText("Hide Details");
					dialog.pack();
				} else {
					pane.setMessage(gT);
					detailsButton.setText("Show Details");
					dialog.pack();
				}
			}
		});
		abortButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				System.exit(1);
			}
		});
		dialog.setVisible(true);
	}
	
	public static void showErrorDialog(Throwable t) {
		showErrorDialog(t, null, null);
	}
}
